package com.raysdata.atlas.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;


@Service
public class MetadataService {

	@Autowired
	private RestTemplate restTemplate;
	@Value("${phinscheduler.host}")
	private String host;
	@Value("${phinscheduler.api.queryDataSource}")
	private String datasource_uri;

	public DataSource getDataSource(String dataSourceId){
		DataSource dataSource = null;
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
		params.add("id", dataSourceId);
		HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);


		ResponseEntity<String> responseEntity = restTemplate.exchange(host+datasource_uri, HttpMethod.POST, requestEntity, String.class);
		JSONObject ret = JSONObject.parseObject(responseEntity.getBody());
		String code = ret.getString("code");
		if ("0".equals(code)) {
			dataSource = JSON.parseObject(ret.getString("data"), DataSource.class);
		}
		return dataSource;
	}
}
